import ImageCompressor from 'image-compressor.js'
const MAX_SIZE = 1048576
class Upimg {
  constructor (url, image) {
    this.image = image
    const xhr = this.xhr = new XMLHttpRequest()  // XMLHttpRequest 对象
    xhr.open('post', url, true) //post方式，url为服务器请求地址，true 该参数规定请求是否异步处理。
    xhr.onload = this._success.bind(this)
    xhr.onerror = this._error.bind(this)
    xhr.upload.onprogress = this._progress.bind(this)
    xhr.upload.onloadstart = this._loadstart.bind(this)
  }

  async compress () {
    const image = this.image
    const quality = MAX_SIZE / image.file.size
    const minImg = await new Promise((resolve, reject) => {
      if (image.file.size < 1024 * 1024 * 2) {
        resolve(image)
      } else {
        m_loading('图片压缩中')
        new ImageCompressor(image.file, {
          quality,
          success: result => {
            m_loading.hide()
            resolve({...image, file: result})
          },
          error: error => {
            m_loading.hide()
            reject(error)
          }
        })
      }
    })
    if (minImg.file.size > MAX_SIZE) {
      m_alert('图片压缩失败,请选择小于2M的图片')
      throw new Error('图片压缩失败,请选择小于2M的图片')
    }
    this.image = minImg
  }

  async start (callback) {
    try {
      m_loading('图片上传中')
      this.callback = callback
      const {file} = this.image
      console.log(file)
      const form = new FormData() // FormData 对象
      form.append('file', file, file.name)
      console.log('压缩后', file.name, Number(file.size / 1024 / 1024).toFixed(2))
      this.xhr.send(form) //开始上传，发送form数据
    } catch (e) {
      m_alert('图片上传失败')
      throw e
    } finally {
      m_loading.hide()
    }
  }

  _success ({target}) {
    var data = JSON.parse(target.responseText)
    if (data.code == 200) {
      this.image.progress = 1
      this.image.state = true
      this.image.cloud = data.msg
      this.callback && this.callback(data.msg)
      m_loading.hide()
    }
  }

  _error () {
    m_alert('图片上传失败')
    this.image.src = null
    this.image.state = false
  }

  _progress ({total, loaded, lengthComputable}) {
    // event.total是需要传输的总字节，event.loaded是已经传输的字节。如果event.lengthComputable不为真，则event.total等于0
    if (lengthComputable) {
      this.image.progress = loaded / total
    }
  }

  _loadstart () {}
}

export default Upimg